{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Numpy练习题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "打印当前Numpy版本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.13.3\n"
     ]
    }
   ],
   "source": [
    "print(np.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构造一个全零的矩阵，并打印其占用的内存大小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=np.zeros((3,3),dtype=np.int32)\n",
    "temp_array\n",
    "#元素个数\n",
    "size=temp_array.size\n",
    "#每个元素占用字节数\n",
    "itemsize=temp_array.itemsize\n",
    "itemsize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "temp_array 矩阵的内存大小36\n"
     ]
    }
   ],
   "source": [
    "print('temp_array 矩阵的内存大小{}'.format(size*itemsize))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "打印一个函数的帮助文档，比如numpy.add"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])\n",
      "\n",
      "Add arguments element-wise.\n",
      "\n",
      "Parameters\n",
      "----------\n",
      "x1, x2 : array_like\n",
      "    The arrays to be added.  If ``x1.shape != x2.shape``, they must be\n",
      "    broadcastable to a common shape (which may be the shape of one or\n",
      "    the other).\n",
      "out : ndarray, None, or tuple of ndarray and None, optional\n",
      "    A location into which the result is stored. If provided, it must have\n",
      "    a shape that the inputs broadcast to. If not provided or `None`,\n",
      "    a freshly-allocated array is returned. A tuple (possible only as a\n",
      "    keyword argument) must have length equal to the number of outputs.\n",
      "where : array_like, optional\n",
      "    Values of True indicate to calculate the ufunc at that position, values\n",
      "    of False indicate to leave the value in the output alone.\n",
      "**kwargs\n",
      "    For other keyword-only arguments, see the\n",
      "    :ref:`ufunc docs <ufuncs.kwargs>`.\n",
      "\n",
      "Returns\n",
      "-------\n",
      "add : ndarray or scalar\n",
      "    The sum of `x1` and `x2`, element-wise.  Returns a scalar if\n",
      "    both  `x1` and `x2` are scalars.\n",
      "\n",
      "Notes\n",
      "-----\n",
      "Equivalent to `x1` + `x2` in terms of array broadcasting.\n",
      "\n",
      "Examples\n",
      "--------\n",
      ">>> np.add(1.0, 4.0)\n",
      "5.0\n",
      ">>> x1 = np.arange(9.0).reshape((3, 3))\n",
      ">>> x2 = np.arange(3.0)\n",
      ">>> np.add(x1, x2)\n",
      "array([[  0.,   2.,   4.],\n",
      "       [  3.,   5.,   7.],\n",
      "       [  6.,   8.,  10.]])\n",
      "Help on NoneType object:\n",
      "\n",
      "class NoneType(object)\n",
      " |  Methods defined here:\n",
      " |  \n",
      " |  __bool__(self, /)\n",
      " |      self != 0\n",
      " |  \n",
      " |  __new__(*args, **kwargs) from builtins.type\n",
      " |      Create and return a new object.  See help(type) for accurate signature.\n",
      " |  \n",
      " |  __repr__(self, /)\n",
      " |      Return repr(self).\n",
      "\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "print(help(np.info(np.add))) #很重要 请牢记"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "创建一个10-49的数组，并将其倒序排列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([48, 48, 46, 46, 46, 44, 43, 41, 41, 41, 40, 39, 39, 37, 36, 34, 33,\n",
       "       32, 32, 28, 27, 25, 25, 25, 25, 25, 24, 23, 23, 23, 21, 21, 20, 19,\n",
       "       18, 16, 15, 13, 10])"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.random.randint(10,50,size=(1,39))\n",
    "temp_array.shape=39,\n",
    "temp_array.sort()\n",
    "temp_array[::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "找到一个数组中不为0的索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 8 1 1 6 3 1 3]\n",
      "[1 8 1 1 6 3 1 3]\n"
     ]
    }
   ],
   "source": [
    "#第一种做法\n",
    "temp_array=[]\n",
    "temp_array=np.random.randint(0,10,8)\n",
    "print(temp_array)\n",
    "temp_array!=0\n",
    "index=np.where(temp_array!=0)\n",
    "print(temp_array[index])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([0, 1, 2, 3, 4, 5, 6, 7], dtype=int64),)"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第二种做法\n",
    "temp_array=[]\n",
    "temp_array=np.random.randint(0,10,8)\n",
    "np.nonzero(temp_array)#注意这个是个新方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "随机构造一个3*3矩阵，并打印其中最大与最小值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "temp_array矩阵最大值:9,最小值：0\n"
     ]
    }
   ],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.random.randint(0,10,size=(3,3))\n",
    "print('temp_array矩阵最大值:{},最小值：{}'.format(temp_array.max(),temp_array.min()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构造一个5*5的矩阵，令其值都为1，并在最外层加上一圈0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#print(np.info(np.pad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n",
       "       [0, 0, 0, 0, 0, 0, 0, 0, 0],\n",
       "       [0, 0, 1, 1, 1, 1, 1, 0, 0],\n",
       "       [0, 0, 1, 1, 1, 1, 1, 0, 0],\n",
       "       [0, 0, 1, 1, 1, 1, 1, 0, 0],\n",
       "       [0, 0, 1, 1, 1, 1, 1, 0, 0],\n",
       "       [0, 0, 1, 1, 1, 1, 1, 0, 0],\n",
       "       [0, 0, 0, 0, 0, 0, 0, 0, 0],\n",
       "       [0, 0, 0, 0, 0, 0, 0, 0, 0]])"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.ones((5,5),dtype=np.int32)\n",
    "#这个函数很重要：图像识别的时候需要在矩阵外围填充数据，这个时候就需要这个函数操作\n",
    "temp_array=np.pad(temp_array,pad_width=2,mode='constant',constant_values=0)#pad_width:代表围上几圈\n",
    "temp_array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构建一个shape为（6，7，8）的矩阵，并找到第100个元素的索引值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 5, 4)"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#注意np提供第几个元素索引值\n",
    "np.unravel_index(100,(6,7,8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[9, 5],\n",
       "       [5, 3]])"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#测试矩阵\n",
    "temp_array=np.random.randint(2,10,size=(2,2))\n",
    "temp_array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array[np.unravel_index(3,(2,2))]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对一个5*5的矩阵做归一化操作\n",
    "*【矩阵归一化操作：套公式来做实际意义后面再说】"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.3771975 ,  0.80510647,  0.45810054,  0.43092459,  0.20419843],\n",
       "       [ 0.69009137,  0.03408308,  0.18984451,  0.64568096,  0.08330328],\n",
       "       [ 0.88207796,  0.7485353 ,  0.52094522,  0.54000619,  0.        ],\n",
       "       [ 0.9467826 ,  0.03960901,  0.43968821,  0.63304101,  0.29663262],\n",
       "       [ 0.95359468,  0.55692882,  1.        ,  0.52240507,  0.6522765 ]])"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=np.random.random((5,5))\n",
    "temp_max=temp_array.max()\n",
    "temp_min=temp_array.min()\n",
    "temp_array=(temp_array-temp_min)/(temp_max-temp_min)\n",
    "temp_array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "找到两个数组中相同的值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "[0 2 4 6 8]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([0, 2, 4, 6, 8])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp1=np.arange(0,10,1)\n",
    "temp2=np.arange(0,10,2)\n",
    "print (temp1)\n",
    "print(temp2)\n",
    "#查找数组相同值操作\n",
    "np.intersect1d(temp1,temp2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "得到今天 明天 昨天的日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "yestoday=np.datetime64('today',\"D\")-np.timedelta64(1,\"D\")\n",
    "today=np.datetime64('today',\"D\")\n",
    "tomorow=np.datetime64('today',\"D\")+np.timedelta64(1,\"D\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2018-02-21')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "yestoday"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2018-02-22')"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "today"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.datetime64('2018-02-23')"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tomorow"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "得到一个月中所有的天"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "day_array=np.arange('2017-10','2017-11',dtype='datetime64[D]')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04',\n",
       "       '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08',\n",
       "       '2017-10-09', '2017-10-10', '2017-10-11', '2017-10-12',\n",
       "       '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16',\n",
       "       '2017-10-17', '2017-10-18', '2017-10-19', '2017-10-20',\n",
       "       '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-24',\n",
       "       '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28',\n",
       "       '2017-10-29', '2017-10-30', '2017-10-31'], dtype='datetime64[D]')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "day_array"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "得到一个数的整数部分\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 8.,  5.,  2.,  2.,  9.,  3.,  9.,  1.,  1.,  2.])"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.random.uniform(0,10,10)\n",
    "temp_array\n",
    "#如何获取整数部分np中已经自带了。\n",
    "np.floor(temp_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "构造一个数组，让它不能被改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "assignment destination is read-only",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-20-07a33d3b0e2b>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mtemp_array\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0muniform\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mtemp_array\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mflags\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwriteable\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mFalse\u001b[0m \u001b[1;31m#设置flags.writeable属性；\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mtemp_array\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: assignment destination is read-only"
     ]
    }
   ],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.random.uniform(0,10,10)\n",
    "temp_array.flags.writeable=False #设置flags.writeable属性；\n",
    "temp_array[0]=1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "打印大数据的部分值，全部值【打印设置】"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "       ..., \n",
       "       [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0., ...,  0.,  0.,  0.]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.set_printoptions(threshold=6) #如果全部展开：threshold=np.nan\n",
    "z = np.zeros((15,15))\n",
    "z"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "找到在一个数组中，最接近一个数的索引[题目含义为：有一个随机数，在数组中找到一个和他最接近的元素的下标]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "28.43422898367868\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "28"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z=np.arange(100)\n",
    "v = np.random.uniform(0,100)\n",
    "print(v)\n",
    "index = (np.abs(z-v)).argmin()\n",
    "z[index]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "32位float类型和32位int类型转换 [array.astype<==> np.asarray（）等价关系，原来数组不变]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.arange(10,dtype=np.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array.astype(np.int32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "打印数组元素位置坐标与数值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.90473352,  0.37024678,  0.72298623],\n",
       "       [ 0.81058152,  0.8417822 ,  0.76541817],\n",
       "       [ 0.29563705,  0.27198527,  0.19389015]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=np.random.rand(3,3)\n",
    "temp_array"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#重点矩阵元素与坐标【很重要】np.ndenumerate "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0) 0.904733519885\n",
      "(0, 1) 0.370246776458\n",
      "(0, 2) 0.722986227299\n",
      "(1, 0) 0.810581519497\n",
      "(1, 1) 0.841782203834\n",
      "(1, 2) 0.765418167611\n",
      "(2, 0) 0.295637049704\n",
      "(2, 1) 0.271985269565\n",
      "(2, 2) 0.193890150311\n"
     ]
    }
   ],
   "source": [
    "for(index,value) in np.ndenumerate(temp_array):\n",
    "    print(index,value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "按照数组的某一列进行排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#考察的是矩阵自定义排序lexsort()或者ndarray.argsort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 3 4]\n",
      " [1 7 5]\n",
      " [7 4 3]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[7, 4, 3],\n",
       "       [0, 3, 4],\n",
       "       [1, 7, 5]])"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=np.random.randint(0,10,(3,3))\n",
    "print(temp_array)\n",
    "#最后一列进行排序\n",
    "temp_array[temp_array[:,-1].argsort()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2 2 6]\n",
      " [3 1 4]\n",
      " [2 0 3]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[2, 2, 6],\n",
       "       [3, 1, 4],\n",
       "       [2, 0, 3]])"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#另一种方法\n",
    "temp_array=np.random.randint(0,10,(3,3))\n",
    "print(temp_array)\n",
    "index=np.lexsort([-1*temp_array[:,-1]])#传入需要排序的列\n",
    "temp_array[index]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "统计数组中每个数值出现的次数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#出现数字统计\n",
    "z = np.array([1,1,1,2,2,3,3,4,5,8])\n",
    "#http://blog.csdn.net/xlinsist/article/details/51346523\n",
    "#bin值为x轴上最大值+1；这样统计顺序就为\n",
    "#bin=7+1=8【最大值】\n",
    "#bin序列：0,1,2,3,4，5,6,7，8\n",
    "#bin次数：0,3,2,2,1,1,0,0,1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 3, 2, 2, 1, 1, 0, 0, 1], dtype=int64)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.bincount(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如何对一个四维数组的最后两维来求和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[99, 74, 77, 89],\n",
       "       [78, 93, 83, 90],\n",
       "       [80, 73, 66, 69],\n",
       "       [73, 81, 75, 97]])"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#维度求和\n",
    "temp_array=np.random.randint(1,10,(4,4,4,4))\n",
    "temp_array.sum(axis=(-2,-1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "交换矩阵中的两行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]\n",
      " [15 16 17 18 19]\n",
      " [20 21 22 23 24]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 5,  6,  7,  8,  9],\n",
       "       [ 0,  1,  2,  3,  4],\n",
       "       [10, 11, 12, 13, 14],\n",
       "       [15, 16, 17, 18, 19],\n",
       "       [20, 21, 22, 23, 24]])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array=np.arange(25).reshape(5,5)\n",
    "print(temp_array)\n",
    "#两行交换\n",
    "temp_array[[0,1]]= temp_array[[1,0]]\n",
    "temp_array\n",
    "#交换两列【无意义操作，可以理解一下矩阵模型知道行可以交换解不变，但是列交换方程解发生变化】\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "找到一个数组中最常出现的数字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "temp_array=[]\n",
    "temp_array=np.random.randint(0,10,50)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "temp_array[np.bincount(temp_array).argmax()]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "快速查找TOP K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# K临近算法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 3 2 4 9 1 5 7 6 8]\n",
      "[9 8 7 6 5]\n",
      "[0 1 2 3 4]\n"
     ]
    }
   ],
   "source": [
    "z=np.arange(10)\n",
    "#随机洗一下牌\n",
    "np.random.shuffle(z)\n",
    "print(z)\n",
    "#Python库Numpy的argpartition函数浅析[已经记录]其实效率相当高\n",
    "n = 5\n",
    "print (z[np.argpartition(-z,n)[:n]])\n",
    "print (z[np.argpartition(z,-n)[:-n]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "去除掉一个数组中，所有元素都相同的数据"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# np.all() 和np.any() 判断数组中所有元素的是否相等"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "a=np.array([1,2,3,4])\n",
    "b=np.array([1,2,3,5])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.all(a==b)#全为真才是真"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 79,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.any(a==b)#其中一个为真就为真"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "z=np.random.randint(0,3,(10,3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[2 2 1]\n",
      " [2 2 1]\n",
      " [2 2 1]\n",
      " [2 2 2]\n",
      " [2 1 1]\n",
      " [2 1 1]\n",
      " [1 1 2]\n",
      " [1 2 1]\n",
      " [0 0 2]\n",
      " [2 0 0]]\n",
      "[False False False  True False False False False False False]\n"
     ]
    }
   ],
   "source": [
    "print(z)\n",
    "e=np.all(z[:,1:] == z[:,:-1],axis=-1)\n",
    "print(e)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 0 2 1]\n",
      " [1 0 2 1]\n",
      " [1 2 1 0]\n",
      " [2 1 1 0]]\n",
      "++++++++++++++\n",
      "[[0 2 1]\n",
      " [0 2 1]\n",
      " [2 1 0]\n",
      " [1 1 0]]\n",
      "++++++++++++++\n",
      "[[1 0 2]\n",
      " [1 0 2]\n",
      " [1 2 1]\n",
      " [2 1 1]]\n",
      "[[False False False]\n",
      " [False False False]\n",
      " [False False False]\n",
      " [False  True False]]\n"
     ]
    }
   ],
   "source": [
    "z=np.random.randint(0,3,(4,4))\n",
    "print(z)\n",
    "print('++++++++++++++')\n",
    "print(z[:,1:])\n",
    "print('++++++++++++++')\n",
    "print(z[:,:-1])\n",
    "print(z[:,1:] == z[:,:-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#本人思考，自生比较无法比较，需要降维度变成两个低纬度比较，两个维度涵盖高纬度所有数据，这样就可进行自身进行比较"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
